﻿using UnityEngine;
using System.Collections;

public class Sound : MonoBehaviour 
{
	// Test stuff, Ignore :)
	//public float testrange;
	//public GameObject test2;
	//public int channel;
	//public bool debug = false;

	// The array that all the sounds will be set in, set to public so you can drag sounds to the object the audio is attached to
	public AudioClip[] sounds;

	// The number of audio sources we should apply. If this is less than 1, it will default to 10
	public int AudioSourceAmount;

	// The overide for the AudioSourceAmount
	public bool OverideLimit = false;

	// The array that all the audiosources spawned in the start function will be stored through. The audio main cycles through this
	AudioSource[] players;

	// Variable used for cycling 
	int cycle;

	// Setting the main sound control to one instance so I can be called anywhere
	public static Sound Main;

	void Start ()
	{
		if (AudioSourceAmount < 1)
			AudioSourceAmount = 10;
		if (AudioSourceAmount > 25 && OverideLimit == false)
		{
			Debug.LogWarning("This is a large amount of sources, do you need this many? Set override to true if you do. Setting source amount to 25.");
			AudioSourceAmount = 25;
		}
		Main = this; // See Above

		// Making a new list and iterating through them to spawn the new Audio Sources
		System.Collections.Generic.List<AudioSource> audioadd = new System.Collections.Generic.List<AudioSource>();
		int i = 0;
		while(i < AudioSourceAmount)
		{
			AudioSource audio = gameObject.AddComponent<AudioSource>();
			audioadd.Add(audio);
			i++;
		}

		// Setting the list to an easier-on-memory array.
		players = audioadd.ToArray();
	}
	/// <summary>
	/// Play Sound with ID specified
	/// </summary>
	/// <returns><c>true</c>, if sound was played, <c>false</c> otherwise.</returns>
	/// <param name="ID">ID</param>
	public static bool PlaySound(int ID)
	{
		if (Main.sounds.Length < ID+1)
		{
			Debug.LogWarning("The ID of the sound you want to play doesn't exist");
			return false;
		}
		Main.players[Main.cycle].clip = Main.sounds[ID];
		Main.players[Main.cycle].Play();
		Main.cycle ++;
		if (Main.cycle == Main.players.Length)
			Main.cycle = 0;
		return true;
	}
	/// <summary>
	/// Play Sound with string specified.
	/// </summary>
	/// <returns><c>true</c>, if sound was played, <c>false</c> otherwise.</returns>
	/// <param name="ID">sound name</param>
	public static bool PlaySound(string clip)
	{
		int iterate = 0;
		bool found = false;
		foreach(AudioClip parse in Main.sounds)
		{
			if (string.Compare(clip, parse.name, ignoreCase:true) == 0)
			{
				PlaySound(iterate);
				found = true;
				return true;
			}
			iterate ++;
		}
		if (found == false)
		{
			Debug.LogWarning("No clip by the name of \""+clip+"\" was found.");
			return false;
		}
		else return true;

	}
}
